import { getValidSelected } from '@/dataTransfer/productCart';
import failImg from '@/images/common/fail.png';
import pRightIcon from '@/images/common/rightIn.png';
import utils from '@/utils/index';
import { Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useState } from 'react';
import { connect } from 'react-redux';
import { ActivityType } from '../constants';
import ScrollDelete from '../ScrollDelete';
import { checkDistributionWay, DistributionWayStatus } from './helper';
import styles from './index.module.scss';
import OrgHeader from './OrgHeader';
import ProductItem from './ProductItem';
import DistributionWayLayout from './DistributionWayLayout';

const Activity = ({ group, orgId, merchantId }) => {
  const goActivity = () => {
    return Taro.navigateTo({
      url: `/giftCardSubPack/salesPromotion/index?id=${group.activityId}&merchantId=${merchantId}&orgId=${orgId}`,
    });
  };

  return (
    <View className="activity-line">
      <View className="activity-wrap">
        <View className="tag customeSalesPromotionLabelStyle">
          <View className="txt customePageStyle">满减</View>
        </View>

        <View className="detail">{group.reduceMoney}</View>
      </View>

      <View className="activity-view" onClick={goActivity}>
        <View className="txt">查看活动</View>
        <Image className="right-icon" src={pRightIcon} />
      </View>
    </View>
  );
};

const OrgView = ({ dispatch, cartSelected, org, onDelete, onProductNumChange }) => {
  const selectList = [...cartSelected];
  const { allIds, validIds, validProducts } = getValidSelected(org);
  const [distributionWayGroup, setDistributionWayGroup] = useState();

  const goShop = useCallback(() => {
    const { type, orgId, merchantId } = org ?? {};
    if (type == 1) {
      //商城跳到商城商品主页
      Taro.navigateTo({
        url: `/mainSubPack/shoppingMall/index?orgId=${orgId}&merchantId=${merchantId}`,
      });
    } else if (type == 4) {
      //外卖跳到外卖店铺
      Taro.navigateTo({
        url: `/mainSubPack/takeOutShop/index?orgId=${orgId}&merchantId=${merchantId}`,
      });
    }
  }, [org]);

  const goProduct = (product) => {
    let { productReleaseId, favouredId } = product;
    if (org?.type == 1) {
      // 商城商品跳到商品详情
      product.id = productReleaseId;
      product.activityId = favouredId;
      utils.goGoodDetail(product, dispatch);
    } else if (org?.type == 4) {
      // 外卖商品跳到外卖店铺
      Taro.navigateTo({
        url: `/mainSubPack/takeOutShop/index?orgId=${org?.orgId}&merchantId=${org?.merchantId}`,
      });
    }
  };

  const changeCartSelect = (ids, curSelectedStatus) => {
    let idList = [];
    if (Array.isArray(ids)) {
      idList = ids;
    } else {
      idList = [ids];
    }
    if (curSelectedStatus) {
      dispatch({
        type: 'productCar/setCartSelectedChange',
        payload: { unChooseIds: idList },
      });
    } else {
      dispatch({
        type: 'productCar/setCartSelectedChange',
        payload: { chooseIds: idList },
      });
    }
  };

  const toggleOrg = () => {
    if (allIds?.length > 0 && allIds?.length == validIds?.length) {
      changeCartSelect(allIds, true);
    } else {
      changeCartSelect(allIds, false);
    }
  };

  const goToBuy = (productList) => {
    const cartIds = productList.map((v) => v.id);
    const productReleaseIds = productList.map(({ productReleaseId }) => productReleaseId);

    dispatch({
      type: 'productCar/setCartShopSelected',
      payload: cartIds,
    });

    dispatch({
      type: 'productCar/setCartShopProductReleaseIds',
      payload: productReleaseIds,
    });

    Taro.navigateTo({
      url: `/orderSubPack/confirmOrder/index?orgId=${org.orgId}&merchantId=${org.merchantId}&type=${org.type}`,
    });
  };

  // 去购买
  const handleBuy = () => {
    if (!validProducts.length) {
      return Taro.showToast({
        mask: true,
        title: '最少购买1件',
        image: failImg,
        duration: 1000,
      });
    }

    const group = checkDistributionWay(validProducts);

    console.log('==============debug for group product distributionWay====', {
      validProducts,
      group,
    });

    if (group === DistributionWayStatus.emptySet) {
      Taro.showToast({
        title: '商品未配置配送方式，请联系商家处理',
        icon: 'none',
        duration: 3000,
      });
      return;
    }

    if (group === DistributionWayStatus.intersection) {
      goToBuy(validProducts);
      return;
    }

    setDistributionWayGroup(group);
  };

  return (
    <View className={styles.OrgView}>
      <DistributionWayLayout
        {...{
          isOpened: !!distributionWayGroup,
          onClose: () => {
            setDistributionWayGroup();
          },
          value: distributionWayGroup,
          onChange: (productList) => {
            goToBuy(productList);
          },
        }}
      />
      <OrgHeader
        {...{
          orgName: org?.orgName,
          onClick: goShop,
          onSelect: toggleOrg,
          isAllSelected: allIds?.length > 0 && allIds?.length == validIds?.length,
        }}
      />

      {org?.groupInfos?.map((group) => {
        const isShowActivity =
          // 参加活动
          group?.isActivity === 1 &&
          // 满减活动才显示
          group.activityType === ActivityType.rebate;

        return (
          <View className="group-item" key={group.activityId}>
            {isShowActivity && (
              <Activity
                {...{
                  group,
                  orgId: org?.orgId,
                  merchantId: org?.merchantId,
                }}
              />
            )}

            <View className="product-list">
              {group?.products?.map((product) => {
                const { id } = product;
                const currentSelect = selectList.includes(id);

                return (
                  <ScrollDelete
                    key={id}
                    onDelete={() => {
                      onDelete(product);
                    }}
                  >
                    <ProductItem
                      {...{
                        className: classNames('productItem', { 'show-activity': isShowActivity }),
                        product,
                        goProduct,
                        isSelected: currentSelect,
                        setSelected: changeCartSelect,
                        onProductNumChange,
                      }}
                    />
                  </ScrollDelete>
                );
              })}
            </View>
          </View>
        );
      })}

      {/* 本期不开发 优惠弹窗 */}
      {/* <SumPriceLayout
        {...{
          totalPrice,
          handleBuy,
          shopSelected,
          isOpened: priceSumIsOpen,
          onClose: () => {
            setPriceSumIsOpen(false);
          },
          onToggle: () => {
            setPriceSumIsOpen(!priceSumIsOpen);
          },
        }}
      /> */}
      {/* <SumPriceBottom
        {...{
          totalPrice: org?.totalPayment ?? 0,
          totalDiscountAmount: org?.totalDiscountAmount ?? 0,
          handleBuy,
          shopSelected: validProducts,
          isOpened: false,
          onSelect: toggleOrg,
          isAllSelected: allIds?.length > 0 && allIds?.length == validIds?.length,
        }}
      /> */}
    </View>
  );
};

export default connect(({ loading, productCar }) => ({
  loading,
  cartSelected: productCar.cartSelected,
}))(OrgView);
